<template>
    <div class="dhzn_gdcoupon"><!-- 商品优惠券接口 -->
        <div class="d_c-content" v-if="pageingstate !== 2">
            <!-- 查询 -->
            <div class="d_c-c-query mb10">
                <el-form :model="selectqurey" label-width="72px" ref="selectqurey" :rules="rules" inline size='mini' class="d_ccq-form">
                    <el-form-item label="查询类型" prop='type'>
                        <el-select v-model="selectqurey.type" clearable>
                            <el-option label="所有优惠券" value="null"></el-option>
                            <el-option label="满减券" value="0"></el-option>
                            <el-option label="折扣券" value="1"></el-option>
                            <el-option label="返利券" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="goodsActivity(),currentPage=1,pageingstate=1">查询</el-button>
                        <el-button type="danger" @click="abolish('selectqurey'),currentPage=1,goodsActivity(),pageingstate=0">取消</el-button>
                    </el-form-item>
                </el-form>
                <span class="bc4a wh br5 f14 p5" @click="pageingstate = 2">添加优惠券</span>
            </div>

            <!-- 数据列表 -->
            <div class="d_c-c-list f14">
                <!-- 数据表 -->
                <table class="d_ccl-tabel tc">
                    <thead>
                        <tr>
                           <tr>
                            <th>ID</th>
                            <th>类型</th>
                            <th>福利</th>
                            <th>总数量</th>
                            <th>剩余数量</th>
                            <th>使用范围</th>
                            <th>商品ID</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in basiclist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.type | filtertype}}</td>
                            <td>
                                <table class="d_cclt-tbody tc">
                                    <tr v-if="item.type === 0">     
                                        <td><span class="ff53">满{{item.full}}</span></td>
                                        <td><span class="ff53">减{{item.reduce}}</span></td>
                                    </tr>
                                    <tr v-else-if="item.type === 1">
                                        <td><span class="ff53">{{item.discount}}折</span></td>
                                    </tr>
                                    <tr v-else>
                                        <td><span class="ff53">{{item.rebate}}￥</span></td>
                                    </tr>
                                </table>
                            </td>
                            <td>{{item.number}}张</td>
                            <td>{{item.surplus}}张</td>
                            <td>{{item.source | filsource}}</td>
                            <td>{{item.goodsid | filname}}</td>
                            <td>
                                <!-- {{item.shelf}} -->
                                <el-switch
                                    class="switch"
                                    @change="shelfswitch(item)"
                                    v-model="item.shelf"
                                    :active-value="1"
                                    :inactive-value="0"
                                    active-text="上架"
                                    inactive-text="下架">
                                </el-switch>
                            </td>
                            <td>
                                <button type="button" class="wh bc4a br5 pt5 pb5" @click="dialogstate=true;for(var i in activityupdate)activityupdate[i]=item[i],activityupdate.key=key"><i class="el-icon-edit-outline"></i>修改</button>
                                <button type="button" class="wh bcfd br5 pt5 pb5" @click="requestdelete(item.id,key)">删除<i class="el-icon-delete"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_rj-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
            <!-- 弹出层 -->
            <el-dialog title="修改优惠券信息" :visible.sync="dialogstate" width="400px" center>
                <el-form :model="activityupdate" label-width="80px" class="d_cc-dialog-form">
                    <el-form-item :label="activityupdate.type===0 ? '满减条件' : '包邮条件'">
                        <el-input v-model="activityupdate.full" placeholder="请输入新的触发条件"></el-input>
                    </el-form-item>

                    <el-form-item label="满减金额" v-show="activityupdate.type===0">
                        <el-input v-model="activityupdate.reduce" placeholder="请输入新的优惠券力度"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer">
                    <el-button @click="dialogstate = false">取 消</el-button>
                    <el-button type="primary" @click="requestupdate">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        
        <!-- 添加模块 -->
        <div class="d_c-add" v-else>
            <div class="d_c-a-title bb1 mb10"><span class="wh bc4a dib br5 p5 mb10 f14" @click="pageingstate = 0">返回列表</span></div>
            <div class="d_c-a-content">
                <el-form :model="activityadd" label-width="90px" ref="activityadd" :rules="rules" class="d_cac-form">
                    <el-form-item label="优惠券类型" prop="type">
                        <el-col :span="5" class="pr5">
                            <el-select v-model="activityadd.type" clearable @change="canceverify(1)">
                                <el-option label="满减券" value="0"></el-option>
                                <el-option label="折扣券" value="1"></el-option>
                                <el-option label="返利券" value="2"></el-option>
                            </el-select>
                        </el-col>

                        <el-col :span="19">
                            <!-- 满减券设置 -->
                            <el-form-item v-if="activityadd.type === '0'" prop="full" ref="couponstate">
                                <el-col :span="3" class="br5">
                                    <el-col :span="4" class="bcfd tc wh">满</el-col>
                                    <el-col :span="20"><el-input v-model='activityadd.full' placeholder="满多少" clearable></el-input></el-col>
                                </el-col>
                                <el-col :span="1" class="tc">—</el-col>
                                <el-col :span="3" class="bc4a tc wh">
                                    <el-col :span="4"><span>减</span></el-col>
                                    <el-col :span="20"><el-input v-model="activityadd.reduce" placeholder="减多少" clearable></el-input></el-col>
                                </el-col>
                            </el-form-item>
                            <!-- 折扣券 -->
                            <el-form-item v-else-if="activityadd.type === '1'" prop="discount" ref="couponstate">
                                <el-col :span="6"><el-input v-model="activityadd.discount" placeholder="设置折扣券"></el-input></el-col>
                            </el-form-item>
                            <!-- 返利券 -->
                            <el-form-item v-else prop="rebate" ref="couponstate">
                                <el-col :span="6"><el-input v-model="activityadd.rebate" placeholder="设置返利券"></el-input></el-col>
                            </el-form-item>
                        </el-col>
                    </el-form-item>

                    <el-form-item prop="number" label="优惠券总数">
                        <el-col :span="6"><el-input v-model="activityadd.number" placeholder="请设置发放优惠券的总数"></el-input></el-col>
                    </el-form-item>
                    <!-- 优惠券的发放方 这个位置在固定商品的优惠券 不用做选择 -->
                    <!-- <el-form-item prop="source" label="使用范围">
                        <el-select v-model="activityadd.source" placeholder="请设置优惠券的使用范围">
                            <el-option label="平台优惠券" value="0"></el-option>                           
                            <el-option label="店铺优惠券" value="1"></el-option>     
                            <el-option label="商品优惠券" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="businessid" v-if="activityadd.source === '1'" label="对应的店铺">
                        <el-select v-model="activityadd.businessid" placeholder="请选择能使用该优惠券的店铺">
                            <el-option v-for="(item,key) in shopname" :key="key" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="goodsid" v-else-if="activityadd.source === '2'" label="对应的商品">
                        <el-select v-model="activityadd.goodsid" placeholder="请选择能使用该优惠券的商品">
                            <el-option v-for="(item,key) in goodsname" :key="key" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item> -->

                    <el-form-item>
                        <el-button type="primary" @click="requestadd">添加</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
let axios = require('axios')
let that
export default {
    components: {},
    data() {
        return {
            id: '',                             //路由传值
            token: '',                          //身份验证
            pageingstate: 0,                    //页面切换分页运行函数的状态管理
            goodsname: '',
            shopname:'',
            basiclist: [],
            // 查询条件绑定对象
            selectqurey: {
                type:'null'
            },
            // 修改字段绑定对象
            activityupdate:{
                id: '',
                type: '',
                full: '',
                reduce: '',
            },
            // 添加字段绑定对象
            activityadd:{
                type: '0',
                full: '',
                reduce: '',
                discount: '',
                rebate: '',
                number: '',
                source: 2,
                shelf: 1
            },
            // 输入验证
            rules:{
                type:[
                    {required:true,message:'请选择优惠券类型',trigger:'change'}
                ],
                full:[
                    {required:true,message:'请输入触发条件',trigger:'blur'}
                ],
                reduce:[
                    {required:true,message:'请输入优惠券力度',trigger:'blur'}
                ],
                discount: [
                    {required:true,message:'请设置折扣券的比例',trigger:'blur'}
                ],
                rebate: [
                    {required:true,message:'请设置返利券的金额',trigger:'blur'}
                ],
                number: [
                    {required:true,message:'请设置发放优惠券数量',trigger:'blur'}
                ],
                source: [
                    {required:true,message:'请设置折扣券的比例',trigger:'change'}
                ],
                businessid: [
                    {required:true,message:'请设置折扣券的比例',trigger:'change'}
                ],
                goodsid: [
                    {required:true,message:'请设置折扣券的比例',trigger:'change'}
                ]
            },
            dialogstate: false,                 //弹出层状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
        };
    },
    filters:{
        filtertype(type){
            if(type === 0){
                type = '满减券'
            }else if(type === 1){
                type = '折扣券'
            }else if(type === 2){
                type = '返现券'
            }else{return}
            return type
        },
        // 发放者
        filsource(type){
            if(type === 0){
                type = '平台优惠券'
            }else if(type === 1){
                type = '店铺优惠券'
            }else if(type === 2){
                type = '商品优惠券'
            }else{return}
            return type
        },
        // 商品名称
        filname(id){
            that.goodsname.forEach((item)=>{
               item.id === id ? id = item.name : ''
            })
            return id
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            let that = this;
            that.pagesize = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        // 添加优惠券
        requestadd(){
            let that = this;
            that.$refs.activityadd.validate((valid)=>{
                if(valid){
                    let data = {surplus:that.activityadd.number,goodsid:that.id};
                    for(var i in that.activityadd) i!=='type' && that.activityadd[i] !== '' ? data[i] = that.activityadd[i] : (
                        i==='type' ? data[i] = Number(that.activityadd[i]) : ''
                    );
                    let updata = JSON.stringify(data);
                    console.log(updata,data)
                    axios({
                        method: 'post',
                        url: '/api/coupon/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=>{ 
                        console.log(resp)
                        data.id = resp.data.data;
                        that.basiclist.length < that.pagesize ? that.basiclist.push(data) : '';
                        that.total += 1;
                        that.pageingstate = 0
                        for(var u in that.activityadd) that.activityadd[u] = "";
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
        },

        // 删除优惠券
        requestdelete(id,key){
            let that = this;
            let updata = JSON.stringify({id: id});
            that.$confirm('此操作将永久删除该文件, 是否继续?', '提示',{
                confirmButtonText:'确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/coupon/delete',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.data === '删除成功！'){
                        that.basiclist.splice(key,1);
                        that.total--
                    }
                }).catch( err=> {console.log(err)})

                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 修改优惠券
        requestupdate(){
            let that = this;
            that.dialogstate = false
            let data = {};
            // console.log(that.activityupdate)
            for(var o in that.activityupdate) o!=='key' && that.activityupdate[o] !== null ? data[o] = that.activityupdate[o] : '';
            let updata = JSON.stringify(data)
            // console.log(data,updata)
            axios({
                method: 'post',
                url: '/api/coupon/update',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                let key = that.activityupdate.key
                for(var u in data) that.basiclist[key][u] === data[u] ? '' : that.basiclist[key][u] = data[u];
            }).catch( err=> {console.log(err)})
        },

        // 修改优惠券状态（上下架）
        shelfswitch(item){
            let that = this;
            let data = {
                id: item.id,
                shelf: item.shelf
            };
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: "/api/coupon/update",
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`,
                },
                data: updata
            })
            .then( resp=> {
                console.log(resp)
            })
            .catch( err=> {console.log(err)})
        },

        // 优惠券
        goodsActivity(){
            let that = this;
            let data = {current: that.currentPage,size:that.pagesize,goodsid:that.id};
            that.selectqurey.type !== null ? data.type = that.selectqurey.type : '';
            let updata = JSON.stringify(data);
            axios({    
                method: 'post',
                url: '/api/coupon/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> { 
                console.log('优惠券',resp)
                that.basiclist = resp.data.data;
                that.total = resp.data.code;
            }).catch( err=>{console.log(err)})
        },

        // 取消查询
        abolish(query){
            this.$refs[query].resetFields()
        },

        // 取消验证
        canceverify(num){
            that.activityadd.full = '',
            that.activityadd.reduce = '',
            that.activityadd.discount = '',
            that.activityadd.rebate = '',
            this.$refs.couponstate.clearValidate()
        },

        // 拿所有店铺ID
        requestshops(){
            let updata = JSON.stringify({current:1,size:100000000})
            axios({
                method: 'post',
                url: '/api/shop/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${that.token}`
                },
                data: updata
            }).then( resp=> {
                // console.log('店铺',resp)
                if(resp.data.message === "请求成功"){
                    that.shopname = resp.data.data.map((item)=>{
                        return{
                            id: item['id'],
                            name: item['name']
                        }
                    })
                }else{return}
            }).catch( err=>{console.log(err)})
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.goodsActivity()
                that.requestshops()
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        let that = this;
        that.id = that.$route.params.aid;
        // that.token = JSON.parse(sessionStorage.getItem('token'))
        that.goodsname = JSON.parse(sessionStorage.getItem('goodsdata'))
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_gdcoupon{
    height: calc(100% - 51px);
}
/* 内容查询、列表和分页 */
.d_c-content{
    height: 100%;
}
/* 查询 */
.d_c-c-query{
    display: flex;
    justify-content: space-between;
}
.d_ccq-form .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin: 0;
}
/* 表单 */
.d_c-c-list{
    display: flex;
    flex-wrap: wrap;
    height: calc(100% - 47px);
}
.d_ccl-tabel{
    width: 100%;
    color: #666666;
    border-collapse: collapse;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}

.d_ccl-tabel thead tr, .d_ccl-tabel tbody tr:hover{
    background-color: #F2F2F2;
}
.d_ccl-tabel tr th,.d_ccl-tabel tr td{
    height: 50px;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid #e0e0e0;
}
.d_ccl-tabel tr td img{
    max-width: 120px;
    max-height: 80px;
}
/* 优惠券 */
.d_cclt-tbody{
    width: 100%;
    border-top: 0 solid #e0e0e0;
    border-right: 0 solid #e0e0e0;
    border-collapse: collapse;
}
.d_cclt-tbody tr td{
    width: 50%;
    border-bottom: 0 solid #e0e0e0;
}
.d_rj-block{
    margin-top: auto;
}
</style>